package com.stox.charting.ui.swing.model.uiUnit;

import java.awt.Graphics;
import java.awt.Rectangle;

import com.stox.charting.ui.swing.model.ChartModel;
import com.stox.charting.ui.swing.model.Theme;
import com.stox.charting.ui.swing.model.price.PriceChartModel;
import com.stox.core.model.IBar;

public class CandleStickUiUnit<T extends IBar> extends PriceBarUiUnit<T> {

	private int x1;
	private int width;
	private int y1;
	private int y2;
	private int y3;
	private int height;

	public CandleStickUiUnit(PriceChartModel<T> model, int index) {
		super(model, index);
	}
	
	@Override
	public void processUi(double width, double factor) {
		ChartModel<T> model = getModel();
		Rectangle r = model.getChart().getVisibleRect();
		setWidth(width);
		this.width = (int)Math.ceil(width);
		x1 = (int)(width*(model.getViewport().getStartIndex() - getIndex() - 1)+width/2);
		setX(x1);
		IBar bar = getValue();
		double min = model.getViewport().getMinimumValueVisible();
		double height = r.getHeight();
		y1 = (int)(height - (bar.getHigh()-min)*factor);
		y2 = (int)(height - (bar.getLow()-min)*factor);
		double y3 = (height - (bar.getClose()-min)*factor);
		double y4 = (height - (bar.getOpen()-min)*factor);
		
		if(y3 > y4){
			this.y3 = (int)Math.ceil(y4);
			this.height = (int)Math.ceil(y3 - y4);
		}else{
			this.y3 = (int)Math.ceil(y3);
			this.height = (int)Math.ceil(y4 - y3);
		}
	}
	
	@Override
	public void paint(Graphics g) {
		g.setColor(Theme.getColours().getBar());
		if(getWidth() < 10){
			g.drawLine(x1,y1,x1, y2);
			g.setColor(getColor());
			g.fillRect(x1-width/3, y3, 2*width/3, height);
		}else{
			double radius = getWidth()/10;
			int diameter = (int)(2*radius);
			g.fillRoundRect((int)(x1-radius), y1, diameter, y2-y1, diameter, diameter);
			g.setColor(getColor());
			g.fillRect(x1-width/3, y3, 2*width/3, height);
			g.setColor(Theme.getColours().getBar());
			g.drawRect(x1-width/3, y3, 2*width/3, height);
		}
		
	}

}
